package com.frogs.ucenter.controller;

import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.component.cache.Cache;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpResponseUtil;

public class AbsController extends BaseController3 {

	//验证码的cookie关键字。
	public static final String COOKIE_KEY_LOGIN_VALIDATE_CODE="lv_back_temp_code";
	private static int EXPIRE=60*10;
	
	@Resource(name="xmemcached")
	private Cache cache;
	
	public void buildValidateCodeCookie(String capText,HttpServletRequest request,HttpServletResponse response,String path,String domain) throws Exception{
		//先删除cookie.
		String _wt_pk_cookie = this.getCookieVal(request, COOKIE_KEY_LOGIN_VALIDATE_CODE);
		if (StringUtil.isEmpty(_wt_pk_cookie)) {
			String s = UUID.randomUUID().toString();
			HttpResponseUtil.setCookie( response, COOKIE_KEY_LOGIN_VALIDATE_CODE, s, domain, path, EXPIRE);//30
			_wt_pk_cookie = s;
		}
		
		if(cache.get(_wt_pk_cookie) != null) {
			cache.remove(_wt_pk_cookie);
		}
		String cryptValue=buildLoginValidateCodeMValue(capText);
		//HttpResponseUtil.setCookie( response, COOKIE_KEY_LOGIN_VALIDATE_CODE, cryptValue, domain, path, EXPIRE);//30
		cache.put(_wt_pk_cookie, cryptValue, EXPIRE);
	}
	
	public String checkValidateCode(String capText,HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		if(StringUtil.isEmpty(capText)){
			return "抱歉，请输入验证码！";
		}
		Cookie[] cookies=request.getCookies();
		if(cookies==null || cookies.length<1){
			return "抱歉，浏览不支持cookie，请开启cookie，或调低安全级别。";//
		}
		
		String _wt_pk_cookie = this.getCookieVal(request, COOKIE_KEY_LOGIN_VALIDATE_CODE);
		if(StringUtil.isEmpty(_wt_pk_cookie)){
			return "抱歉，获取cookie有误";
		}
		String cacheValue = (String) cache.get(_wt_pk_cookie);
		if(StringUtil.isEmpty(cacheValue)) {
			return "抱歉，验证码超时！请更换新的验证码";
		}
		String mValue=buildLoginValidateCodeMValue(capText);
		if(mValue.equalsIgnoreCase(cacheValue)){
			if(cache.get(_wt_pk_cookie) != null) {
				cache.remove(_wt_pk_cookie);
			}
			return "success";
		}
		return "抱歉，验证码输入错误！";
	}
	/**
	 * 验证码的加密数据。
	 * @param text
	 * @return
	 */
	private static  String buildLoginValidateCodeMValue(String text){
		String str="&^%HJdf"+text+"dfd^&56";
		String mValue=StringUtil.md5(str);
		return mValue;
	}
}
